//
// Created by wuji on 2020/5/19.
//

#include "client.h"
#include "sys/socket.h"
#include <netdb.h>
#include <unistd.h>
#include <memory.h>
#include "stdio.h"


int client::Connect(char *ip, const int port) {
	client_fd = socket(AF_INET,SOCK_STREAM,0);
	struct hostent* h; // ip地址信息的数据结构
	if ( (h=gethostbyname(ip))==0){
		close(client_fd);
		client_fd=0;
		return false;
	}
	struct sockaddr_in servaddr;
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	memcpy(&servaddr.sin_addr,h->h_addr,h->h_length);
	if (connect(client_fd, (struct sockaddr *)&servaddr,sizeof(servaddr)) != 0){ close(client_fd); return -1; }
	return client_fd;
}

int client::Send(int fd,char * buf,const int buflen){
	int cnt = send(fd,(char *)buf,buflen,0);
	if (cnt<=0){
		printf("client send fail");
		return -1;
	}
	return cnt;
}

int client::Recv(int fd,char *buf,int size) {
	int cnt =  recv(fd,(char *)buf,size,1024);
	if (cnt<=0){
		printf("client recv fail");
		return -1;
	}
	return cnt;
}